#include "warningmanage.h"
#include "ui_warningmanage.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
#include <QStringList>
#include <QRegularExpression>

WarningManage::WarningManage(QWidget *parent)
    : QWidget(parent), m_isEditing(false), m_editedRow(-1),m_alarmInterval(20)
{
    m_pSqliteManage = new SqliteManage;
    m_pLog = LogClass::getInstance();
    if (!m_pSqliteManage->openDatabase("C:/Users/shafl/Desktop/FrameWork/test.db")) {
        qDebug() << "Failed to open database:" << m_pSqliteManage->lastError();
    }
    initEmailSettings();
    setupModels();
    setupUI();
}

WarningManage::~WarningManage()
{
    m_pSqliteManage->closeDatabase();
    delete m_pSqliteManage;
    delete m_emailSettings;
}

void WarningManage::setUserName(QString &name)
{
    this->username = name;
}

void WarningManage::initEmailSettings()///////////////////////////////////////////////////////////////////
{
    m_emailSettings = new QSettings("C:/Users/shafl/Desktop/IoTDeviceManage/src/config/config.ini", QSettings::IniFormat, this);

    // 初始化默认配置
    if (!m_emailSettings->contains("smtp/server")) {
        m_emailSettings->setValue("smtp/server", "smtp.qq.com");
        m_emailSettings->setValue("smtp/port", 465);
        m_emailSettings->setValue("smtp/username", "shafl@qq.com");
        m_emailSettings->setValue("smtp/password", "zqmhujzefdvjecca");
        m_emailSettings->setValue("smtp/ssl", true);
        m_emailSettings->setValue("Recipients/primary", "17839550102@139.com");
        //m_emailSettings->setValue("Recipients/secondary", "backup@example.com");
        m_emailSettings->sync();
    }
}

void WarningManage::setupModels()
{
    // 告警规则模型
    m_rulesModel = new QSqlTableModel(this,m_pSqliteManage->getDB());
    m_rulesModel->setTable("alarm_rules");
    m_rulesModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    if (!m_rulesModel->select()) {
        qDebug() << "告警规则模型查询失败:" << m_rulesModel->lastError().text();
    } else {
        qDebug() << "告警规则模型加载成功，行数:" << m_rulesModel->rowCount();
    }


    // 设置表头
    m_rulesModel->setHeaderData(0, Qt::Horizontal, "规则ID");
    m_rulesModel->setHeaderData(1, Qt::Horizontal, "设备ID");
    m_rulesModel->setHeaderData(2, Qt::Horizontal, "规则描述");
    m_rulesModel->setHeaderData(3, Qt::Horizontal, "告警条件");
    m_rulesModel->setHeaderData(4, Qt::Horizontal, "告警动作");

    // 告警记录模型（使用关联表模型以显示设备名称而非ID）
    m_recordsModel = new QSqlRelationalTableModel(this,m_pSqliteManage->getDB());
    m_recordsModel->setTable("alarm_records");
    m_recordsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置表头
    m_recordsModel->setHeaderData(0, Qt::Horizontal, "告警ID");
    m_recordsModel->setHeaderData(1, Qt::Horizontal, "设备ID");
    m_recordsModel->setHeaderData(2, Qt::Horizontal, "时间戳");
    m_recordsModel->setHeaderData(3, Qt::Horizontal, "告警内容");
    m_recordsModel->setHeaderData(4, Qt::Horizontal, "处理状态");
    m_recordsModel->setHeaderData(5, Qt::Horizontal, "处理备注");

    if (!m_recordsModel->select()) {
        qDebug() << "告警规则模型查询失败:" << m_recordsModel->lastError().text();
        m_pLog->log(m_pSqliteManage,SYSTEM_LOG,INFO,QString("告警规则数据加载失败"));
    } else {
        qDebug() << "告警规则模型加载成功，行数:" << m_recordsModel->rowCount();
    }

    // 用于过滤的代理模型
    m_recordsProxyModel = new QSortFilterProxyModel(this);
    m_recordsProxyModel->setSourceModel(m_recordsModel);
    m_recordsProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
}

void WarningManage::setupUI()
{
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(10);

    // ===== 告警规则管理区域 =====
    QGroupBox *rulesGroupBox = new QGroupBox("告警规则管理", this);
    rulesGroupBox->setMinimumHeight(250);
    QVBoxLayout *rulesLayout = new QVBoxLayout(rulesGroupBox);

    // 规则表格
    m_rulesTableView = new QTableView(this);
    m_rulesTableView->setModel(m_rulesModel);
    m_rulesTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_rulesTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    m_rulesTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_rulesTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    rulesLayout->addWidget(m_rulesTableView);

    // 规则操作按钮
    QHBoxLayout *rulesButtonLayout = new QHBoxLayout();
    rulesButtonLayout->setSpacing(10);

    m_addRuleButton = new QPushButton("添加告警规则", this);
    m_addRuleButton->setMinimumWidth(120);
    m_deleteRuleButton = new QPushButton("删除告警规则", this);
    m_deleteRuleButton->setMinimumWidth(120);
    m_editRuleButton = new QPushButton("修改告警规则", this);
    m_editRuleButton->setMinimumWidth(120);
    m_saveRuleButton = new QPushButton("保存修改", this);
    m_saveRuleButton->setMinimumWidth(120);
    m_cancelButton = new QPushButton("取消", this);
    m_cancelButton->setMinimumWidth(120);

    m_saveRuleButton->setEnabled(false);
    m_cancelButton->setEnabled(false);

    rulesButtonLayout->addWidget(m_addRuleButton);
    rulesButtonLayout->addWidget(m_deleteRuleButton);
    rulesButtonLayout->addWidget(m_editRuleButton);
    rulesButtonLayout->addWidget(m_saveRuleButton);
    rulesButtonLayout->addWidget(m_cancelButton);
    rulesLayout->addLayout(rulesButtonLayout);

    // ===== 告警记录查询区域 =====
    QGroupBox *recordsGroupBox = new QGroupBox("告警记录查询", this);
    recordsGroupBox->setMinimumHeight(300);
    QVBoxLayout *recordsLayout = new QVBoxLayout(recordsGroupBox);

    // 查询条件区域 - 使用扩展的网格布局
    QGridLayout *filterLayout = new QGridLayout();
    filterLayout->setSpacing(10);
    filterLayout->setColumnStretch(1, 2); // 设备名称输入框占据2份空间
    filterLayout->setColumnStretch(3, 2); // 状态选择框占据2份空间
    filterLayout->setColumnStretch(5, 1); // 时间范围标签占据1份空间

    // 第一行：设备名称、处理状态和修改告警记录按钮
    QLabel *deviceLabel = new QLabel("设备名称:", this);
    m_deviceFilterEdit = new QLineEdit(this);

    QLabel *statusLabel = new QLabel("处理状态:", this);
    m_statusFilterCombo = new QComboBox(this);
    m_statusFilterCombo->addItem("全部", "");
    m_statusFilterCombo->addItem("未处理", "未");
    m_statusFilterCombo->addItem("已处理", "已");

    m_editRecordButton = new QPushButton("修改告警记录", this);
    m_editRecordButton->setMinimumWidth(120);

    filterLayout->addWidget(deviceLabel, 0, 0);
    filterLayout->addWidget(m_deviceFilterEdit, 0, 1);
    filterLayout->addWidget(statusLabel, 0, 2);
    filterLayout->addWidget(m_statusFilterCombo, 0, 3);
    filterLayout->addWidget(m_editRecordButton, 0, 4, 1, 2); // 按钮跨越两列

    // 第二行：时间范围和查询按钮
    QLabel *timeRangeLabel = new QLabel("时间范围:", this);
    m_startTimeFilter = new QDateTimeEdit(this);
    m_startTimeFilter->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    m_startTimeFilter->setDateTime(QDateTime::currentDateTime().addDays(-7));

    QLabel *toLabel = new QLabel("至", this);
    m_endTimeFilter = new QDateTimeEdit(this);
    m_endTimeFilter->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    m_endTimeFilter->setDateTime(QDateTime::currentDateTime());

    m_filterButton = new QPushButton("查询", this);
    m_filterButton->setMinimumWidth(80);

    filterLayout->addWidget(timeRangeLabel, 1, 0);
    filterLayout->addWidget(m_startTimeFilter, 1, 1);
    filterLayout->addWidget(toLabel, 1, 2);
    filterLayout->addWidget(m_endTimeFilter, 1, 3);
    filterLayout->addWidget(m_filterButton, 1, 4, 1, 2); // 查询按钮跨越两列

    recordsLayout->addLayout(filterLayout);

    // 记录表格
    m_recordsTableView = new QTableView(this);
    m_recordsTableView->setModel(m_recordsProxyModel);
    m_recordsTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_recordsTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    m_recordsTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_recordsTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    recordsLayout->addWidget(m_recordsTableView);

    // 添加到主布局
    mainLayout->addWidget(rulesGroupBox);
    mainLayout->addWidget(recordsGroupBox);

    // 连接信号和槽
    connect(m_addRuleButton, &QPushButton::clicked, this, &WarningManage::addAlarmRule);
    connect(m_deleteRuleButton, &QPushButton::clicked, this, &WarningManage::deleteAlarmRule);
    connect(m_editRuleButton, &QPushButton::clicked, this, &WarningManage::editAlarmRule);
    connect(m_saveRuleButton, &QPushButton::clicked, this, &WarningManage::saveAlarmRule);
    connect(m_cancelButton, &QPushButton::clicked, this, &WarningManage::cancelEdit);
    connect(m_filterButton, &QPushButton::clicked, this, &WarningManage::filterAlarmRecords);
    connect(m_editRecordButton, &QPushButton::clicked, this, &WarningManage::editAlarmRecord);
}

void WarningManage::addAlarmRule()
{
    // 添加新行
    int row = m_rulesModel->rowCount();
    m_rulesModel->insertRow(row);

    // 使表格可编辑
    m_rulesTableView->setEditTriggers(QAbstractItemView::AllEditTriggers);
    m_rulesTableView->edit(m_rulesModel->index(row, 1)); // 开始编辑设备ID列

    // 更新按钮状态
    m_addRuleButton->setEnabled(false);
    m_deleteRuleButton->setEnabled(false);
    m_editRuleButton->setEnabled(false);
    m_saveRuleButton->setEnabled(true);
    m_cancelButton->setEnabled(true);

    m_isEditing = true;
    m_editedRow = row;
    m_pLog->log(m_pSqliteManage,OPERATION_LOG,INFO,QString("添加了告警规则"),
                m_pSqliteManage->getUserIdByName(username));
}

void WarningManage::deleteAlarmRule()
{
    QModelIndexList selectedRows = m_rulesTableView->selectionModel()->selectedRows();
    if (selectedRows.isEmpty()) {
        QMessageBox::information(this, "提示", "请先选择要删除的告警规则");
        return;
    }

    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除",
                                                           "确定要删除选中的告警规则吗？",
                                                           QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        // 按从大到小的顺序删除，避免索引问题
        for (int i = selectedRows.size() - 1; i >= 0; --i) {
            m_rulesModel->removeRow(selectedRows[i].row());
        }

        if (!m_rulesModel->submitAll()) {
            QMessageBox::critical(this, "错误", "删除失败: " + m_rulesModel->lastError().text());
            m_rulesModel->revertAll();
        }
        m_pLog->log(m_pSqliteManage,OPERATION_LOG,INFO,QString("删除了告警规则"),
                    m_pSqliteManage->getUserIdByName(username));
    }
}

void WarningManage::editAlarmRule()
{
    QModelIndexList selectedRows = m_rulesTableView->selectionModel()->selectedRows();
    if (selectedRows.isEmpty()) {
        QMessageBox::information(this, "提示", "请先选择要修改的告警规则");
        return;
    }

    m_editedRow = selectedRows.first().row();

    // 使表格可编辑
    m_rulesTableView->setEditTriggers(QAbstractItemView::AllEditTriggers);
    m_rulesTableView->edit(m_rulesModel->index(m_editedRow, 2)); // 开始编辑描述列

    // 更新按钮状态
    m_addRuleButton->setEnabled(false);
    m_deleteRuleButton->setEnabled(false);
    m_editRuleButton->setEnabled(false);
    m_saveRuleButton->setEnabled(true);
    m_cancelButton->setEnabled(true);

    m_isEditing = true;
    m_pLog->log(m_pSqliteManage,OPERATION_LOG,INFO,QString("修改了告警规则"),
                m_pSqliteManage->getUserIdByName(username));
}

void WarningManage::saveAlarmRule()
{
    if (!m_rulesModel->submitAll()) {
        QMessageBox::critical(this, "错误", "保存失败: " + m_rulesModel->lastError().text());
        m_rulesModel->revertAll();
    } else {
        QMessageBox::information(this, "成功", "告警规则已保存");
    }

    // 恢复表格状态
    m_rulesTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 更新按钮状态
    m_addRuleButton->setEnabled(true);
    m_deleteRuleButton->setEnabled(true);
    m_editRuleButton->setEnabled(true);
    m_saveRuleButton->setEnabled(false);
    m_cancelButton->setEnabled(false);

    m_isEditing = false;
    m_editedRow = -1;
}

void WarningManage::cancelEdit()
{
    m_rulesModel->revertAll();

    // 恢复表格状态
    m_rulesTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 更新按钮状态
    m_addRuleButton->setEnabled(true);
    m_deleteRuleButton->setEnabled(true);
    m_editRuleButton->setEnabled(true);
    m_saveRuleButton->setEnabled(false);
    m_cancelButton->setEnabled(false);

    m_isEditing = false;
    m_editedRow = -1;
}

void WarningManage::filterAlarmRecords()
{
    QString deviceName = m_deviceFilterEdit->text();
    QString status = m_statusFilterCombo->currentText();
    QDateTime startTime = m_startTimeFilter->dateTime();
    QDateTime endTime = m_endTimeFilter->dateTime();

    if (startTime > endTime) {
        QMessageBox::warning(this, "时间错误", "开始时间不能晚于结束时间");
        return;
    }

    // 构建过滤条件
    QString filter;
    QStringList conditions;

    if (!deviceName.isEmpty()) {
        conditions.append(QString("device_id IN (SELECT device_id FROM devices WHERE name LIKE '%%1%')")
                          .arg(deviceName));
    }

    if (status != "全部") {
        conditions.append(QString("status = '%1'").arg(status));
    }

    // 使用ISO格式时间
    conditions.append(QString("datetime(timestamp) BETWEEN datetime('%1') AND datetime('%2')")
                   .arg(startTime.toString(Qt::ISODate))
                   .arg(endTime.toString(Qt::ISODate)));

    filter = conditions.join(" AND ");
    qDebug() << "Filter condition:" << filter;

    // 应用过滤
    m_recordsModel->setFilter(filter);
    if (!m_recordsModel->select()) {
        qDebug() << "Select failed:" << m_recordsModel->lastError().text();
    }

    // 强制刷新视图
    m_recordsTableView->reset();

    // 调试输出
    qDebug() << "Row count:" << m_recordsModel->rowCount();
    qDebug() << "Actual SQL:" << m_recordsModel->query().executedQuery();

    if (m_recordsModel->rowCount() == 0) {
        QMessageBox::information(this, "查询结果", "未找到符合条件的告警记录");
    }
}
void WarningManage::editAlarmRecord()
{
    QModelIndexList selectedRows = m_recordsTableView->selectionModel()->selectedRows();
    if (selectedRows.isEmpty()) {
        QMessageBox::information(this, "提示", "请先选择要修改的告警记录");
        return;
    }

    QModelIndex index = m_recordsProxyModel->mapToSource(selectedRows.first());
    AlarmRecordEditDialog dialog(index, this);

    if (dialog.exec() == QDialog::Accepted) {
        QString status = dialog.getStatus();
        QString note = dialog.getNote();

        // 更新模型数据
        m_recordsModel->setData(index.siblingAtColumn(4), status);
        m_recordsModel->setData(index.siblingAtColumn(5), note);

        if (!m_recordsModel->submitAll()) {
            QMessageBox::critical(this, "错误", "保存失败: " + m_recordsModel->lastError().text());
            m_recordsModel->revertAll();
        } else {
            QMessageBox::information(this, "成功", "告警记录已更新");
            m_pLog->log(m_pSqliteManage,OPERATION_LOG,INFO,QString("修改了告警记录"),
                        m_pSqliteManage->getUserIdByName(username));
        }
    }
}

// 新增：处理实时数据点
void WarningManage::processDataPoint(int deviceId, const DataPoint &data)
{
    // 在processDataPoint开始时调用
    if (!checkEmailConfig()) {
        qWarning() << "短信通知未配置，跳过发送";
        return;
    }

    // 获取该设备的所有告警规则
    QList<QMap<QString, QVariant>> rules = getAlarmRulesForDevice(deviceId);
    if (rules.isEmpty()) {
        qDebug() << "设备" << deviceId << "没有配置告警规则";
        return;
    }

    // 检查每个规则
    foreach (const auto &rule, rules) {
        if (checkCondition(rule, data)) {
            // 检查是否在告警间隔内
            if (isWithinAlarmInterval(deviceId)) {
                qDebug() << "设备" << deviceId << "在告警间隔内，不重复发送";
                continue;
            }

            // 生成告警内容
            QString description = rule["description"].toString();
            QString content = QString("设备%1触发告警: %2 (温度: %3, 湿度: %4, 光照: %5)")
                               .arg(deviceId)
                               .arg(description)
                               .arg(data.temperature)
                               .arg(data.humidity)
                               .arg(data.light);

            // 发送短信通知
            sendAlertNotification(deviceId, content);

            // 记录告警
            logAlarmRecord(deviceId, content);

            // 更新最近告警时间
            m_lastAlarmTimes[deviceId] = QDateTime::currentDateTime();

            qDebug() << "设备" << deviceId << "告警触发:" << content;
        }
    }
}

void WarningManage::sendAlertNotification(int deviceId, const QString &message) {
    // 1. 获取配置
    QString recipient = m_emailSettings->value("Recipients/primary").toString();
    QString smtpServer = m_emailSettings->value("smtp/server").toString();
    int port = m_emailSettings->value("smtp/port").toInt();
    QString username = m_emailSettings->value("smtp/username").toString();
    QString password = m_emailSettings->value("smtp/password").toString();
    bool useSsl = m_emailSettings->value("smtp/ssl").toBool();

    // 2. 验证配置
    if (recipient.isEmpty() || smtpServer.isEmpty() || username.isEmpty()) {
        qWarning() << "短信通知配置不完整";
        return;
    }

    // 3. 构建邮件内容（精简版）
    QString emailContent = QString(
        "From: %1\n"
        "To: %2\n"
        "Subject: \n\n"  // 空主题
        "[设备%3告警] %4"  // 内容格式
    ).arg(username).arg(recipient).arg(deviceId).arg(message.left(140)); // 限制长度

    // 4. 使用QProcess调用命令行工具发送（兼容性更好）
    sendViaCommandLine(smtpServer, port, username, password, recipient, emailContent);
}

void WarningManage::sendViaCommandLine(const QString &smtpServer, int port,
                                     const QString &username, const QString &password,
                                     const QString &recipient, const QString &content) {
    QString program = "curl";
    QStringList arguments;

    // 构建Base64编码的用户名和密码
    QByteArray encodedUsername = QByteArray(username.toUtf8()).toBase64();
    QByteArray encodedPassword = QByteArray(password.toUtf8()).toBase64();

    // 使用AUTH LOGIN方式
    arguments << "--url" << QString("smtps://%1:%2").arg(smtpServer).arg(port)
              << "--mail-from" << username
              << "--mail-rcpt" << recipient
              << "--user" << QString("%1:%2").arg(username).arg(password)
              << "--upload-file" << "-"
              << "-v";

    QProcess *process = new QProcess(this);
    process->start(program, arguments);

    if (!process->waitForStarted()) {
        qWarning() << "无法启动curl进程";
        process->deleteLater();
        return;
    }

    process->write(content.toUtf8());
    process->closeWriteChannel();

    connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            [=](int exitCode, QProcess::ExitStatus status) {
        if (exitCode == 0) {
            qDebug() << "短信通知发送成功";
        } else {
            qWarning() << "发送失败, 错误码:" << exitCode
                      << "错误输出:" << process->readAllStandardError();
        }
        process->deleteLater();
    });
}

bool WarningManage::checkEmailConfig() const {
    return !m_emailSettings->value("smtp/server").toString().isEmpty() &&
           !m_emailSettings->value("smtp/username").toString().isEmpty();
}



// 新增：获取设备的告警规则
QList<QMap<QString, QVariant>> WarningManage::getAlarmRulesForDevice(int deviceId)
{
    QList<QMap<QString, QVariant>> rules;
    QSqlQuery query(m_pSqliteManage->getDB());
    query.prepare("SELECT rule_id, description, condition, action FROM alarm_rules WHERE device_id = :deviceId");
    query.bindValue(":deviceId", deviceId);

    if (query.exec()) {
        while (query.next()) {
            QMap<QString, QVariant> rule;
            rule["rule_id"] = query.value("rule_id");
            rule["description"] = query.value("description");
            rule["condition"] = query.value("condition");
            rule["action"] = query.value("action");
            rules.append(rule);
        }
    } else {
        qDebug() << "查询设备告警规则失败:" << query.lastError().text();
    }
    return rules;
}

// 新增：检查条件是否满足
bool WarningManage::checkCondition(const QMap<QString, QVariant> &rule, const DataPoint &data)
{
    QString condition = rule["condition"].toString();
    if (condition.isEmpty()) {
        return false;
    }

    QJSEngine engine;
    engine.globalObject().setProperty("light", data.light);
    engine.globalObject().setProperty("temperature", data.temperature);
    engine.globalObject().setProperty("humidity", data.humidity);

    QJSValue result = engine.evaluate(condition);

    // 兼容性检查方式（适用于所有Qt5版本）
    if (result.isError()) {  // 这是最通用的检查方法
        qDebug() << "条件表达式执行错误:"
                 << result.toString()
                 << "\n表达式内容:" << condition;
        return false;
    }

    if (!result.isBool()) {
        qDebug() << "条件表达式必须返回布尔值，实际返回:"
                 << result.toString();
        return false;
    }

    return result.toBool();
}

// 新增：检查是否在告警间隔内
bool WarningManage::isWithinAlarmInterval(int deviceId)
{
    QDateTime lastTime = m_lastAlarmTimes.value(deviceId, QDateTime());
    if (lastTime.isValid()) {
        qint64 secs = lastTime.secsTo(QDateTime::currentDateTime());
        return secs < m_alarmInterval;
    }
    return false;
}



// 新增：记录告警到数据库
void WarningManage::logAlarmRecord(int deviceId, const QString &content)
{
    QSqlQuery query(m_pSqliteManage->getDB());
    query.prepare("INSERT INTO alarm_records (device_id, timestamp, content, status, note) "
                  "VALUES (:deviceId, :timestamp, :content, '未处理', '')");
    query.bindValue(":deviceId", deviceId);
    query.bindValue(":timestamp", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    query.bindValue(":content", content);

    if (!query.exec()) {
        qDebug() << "记录告警失败:" << query.lastError().text();
    } else {
        // 刷新告警记录表格
        m_pLog->log(m_pSqliteManage,ALARM_LOG,CRITICAL,"设备警告："+content,
                    m_pSqliteManage->getUserIdByName(username),deviceId);
        m_recordsModel->select();
    }
}
